<?php

/*
 * Copyright (C) 2010 Emanuele Colonnelli <emanuele.colonnelli@phpstruct.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

namespace org\phpstruct\core;

use org\phpstruct\util;

define('TPL_PATH', (sprintf('%s%stemplates%s',
                $_SERVER['DOCUMENT_ROOT'],
                DIRECTORY_SEPARATOR,
                DIRECTORY_SEPARATOR
        )));

/**
 * Description of T
 *
 * @author Emanuele Colonnelli <emanuele.colonnelli@phpstruct.org>
 */
class T {

    private static $instance;
    protected static $vars = array();
    protected static $template;

    private function __construct() {
        self::$instance = $this;
    }

    /**
     * @return Rebel_Template_Loader
     */
    private function getInstance() {
        return self::$instance ? self::$instance : new self();
    }

    const TPL_EXT = 'php';

    public static function setTemplate($strTemplate) {
        self::$template = $strTemplate;
    }

    public static function assign($name, $value) {
        self::$vars[$name] = $value;
    }

    public static function load($template, $vars=array(), $is_include=false, $altpath=null) {

        extract(self::$vars);
        extract($vars);
        
        $search_path = $altpath ? $altpath : TPL_PATH;

        if(isset(self::$template)) {
            $template = self::$template . "_{$template}";
        }

        $path = self::find($template, $search_path);
        
        if ($path) {
            if (isset($_REQUEST['DEBUG'])) {
                print('<div style="padding:20px;position:relative;display:block;border:1px solid red;background-color:#cccccc;color:#ffffff;font-weight:bold;>');
            }
            if (\file_exists($path)) {
                include($path);
            } else {
                die($path);
                return false;
            }

            if (isset($_REQUEST['DEBUG'])) {
                print("<div style='display:block;position:relative;top:0px;left:0px;'>$path</div></div>");
            }
        } else {
            Logger::log("COULD NOT FIND TEMPLATE $search_path.$template");
            return false;
        }
    }

    private static function find($template, $path) {
        $cp = $template; //str_replace("_",DIRECTORY_SEPARATOR,$template);
        $fullpath = util\StdLib::normalizePath(sprintf('%s%s.%s', $path, $cp, self::TPL_EXT));

        if (is_file($fullpath)) {
            return $fullpath;
        } elseif (is_file($fullpath = sprintf('%s%s.%s', util\StdLib::normalizePath($path), str_replace("_", DIRECTORY_SEPARATOR, $template), self::TPL_EXT))) {
            return $fullpath;
        } else {
            Logger::log("COULD NOT FIND TEMPLATE $fullpath");
            throw new \Exception("COULD NOT FIND TEMPLATE $fullpath");
        }
    }

    public static function get($varname) {
        return isset(self::$vars[$varname]) ? self::$vars[$varname] : null;
    }

    public static function debug() {

        $files = get_included_files();

        print "<table style=\"border:1px solid #333333;background-color:#dfdfdf;color:blue;\">";
        foreach (self::$vars as $k => $v) {
            print "<tr>";
            print "<td style=\"font-weight:bold;\">\${$k}</td>";
            print "<td><xmp>";
            print_r($v);
            print "</xmp></td></tr>";
        }
        print "<tr><td colspan=\"2\"><h3>Elenco templates inclusi</h3></td></tr>";
        foreach ($files as $k => $v) {
            if (preg_match(sprintf("~\%stemplates~", DIRECTORY_SEPARATOR), $v)) {
                $path = str_replace($_SERVER['DOCUMENT_ROOT'], "", $v);
                print "<tr>";
                print "<td>{$k}</td>";
                print "<td>";
                print $path;
                print "</td></tr>";
            }
        }
        print "</table>";
    }

    public function __set($varname, $value) {
        self::$vars[$varname] = $value;
    }

    public function __get($varname) {
        return isset(self::$vars[$varname]) ? self::$vars[$varname] : null;
    }

    public static function _($string, $print=true, $words=null) {
        if ($words) {

            if ($print) {
                print self::g(\_($string), $words);
            } else {
                return self::g(\_($string), $words);
            }
        } else {
            if ($print) {
                print \_($string);
            } else {
                return \_($string);
            }
        }
    }

    private static function pattern_replacement($item) {
        return "/\{" . $item . "\}/";
    }

    private static function g($string, $vars) {

        preg_match_all("~\{([^\}]+)\}~e", $string, $ret);

        foreach ($ret[1] as $reqvar) {
            if (!isset($vars[$reqvar])) {
                trigger_error("This string needs variable $reqvar to be defined!", E_USER_NOTICE);
            }
        }

        $k = array_keys($vars);
        $r = array_values($vars);

        $k = array_map('self::pattern_replacement', $k);

        return preg_replace($k, $r, $string);
    }

}

